<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { fetchAddHosp, fetchEditHosp } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions /* ,roleIdOptions */ } from '@/constants/business';

defineOptions({
  name: 'HospOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData: Api.SystemManage.Hosp | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.hosp.addHosp'),
    edit: $t('page.manage.hosp.editHosp')
  };
  return titles[props.operateType];
});

// type Model = Pick<
//   Api.SystemManage.User,
//   'userName' | 'userGender' | 'nickName' | 'userPhone' | 'userEmail' | 'userRoles' | 'status'
// >;
type Model = Pick<
  Api.SystemManage.Hosp,
  "hospName"  | "hospLoc"| "deleteFlag"| "hospId"
>;
const model = ref(createDefaultModel(props.rowData));

function createDefaultModel(rowData?: Api.SystemManage.Hosp | null): Model {
  return {
    deleteFlag: rowData?.deleteFlag ?? 1, // 如果 rowData 或 deleteFlag 不存在，设置默认值为 1
    hospName: rowData?.hospName ?? ' 医院 ',
    hospLoc: rowData?.hospLoc ?? ' 医院地址 ',
    hospId: rowData?.hospId ?? '1'
  };
}
// 验证规则 hospName与deleteFlag必填
type RuleKey = Extract<keyof Model, 'hospName' | 'deleteFlag'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  hospName: defaultRequiredRule,
  deleteFlag: defaultRequiredRule,

};

// /** the enabled role options */
// const roleOptions = ref<CommonType.Option<string>[]>([]);
//
// async function getRoleOptions() {
//   const { error, data } = await fetchGetAllRoles();
//
//   if (!error) {
//     const options = data.map(item => ({
//       label: item.roleName,
//       value: item.roleCode
//     }));
//
//     // the mock data does not have the roleCode, so fill it
//     // if the real request, remove the following code
//     // const userRoleOptions = model.value.userRoles.map(item => ({
//     //   label: item,
//     //   value: item
//     // }));
//     // end
//
//     roleOptions.value = [...userRoleOptions, ...options];
//   }
// }

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  console.log(props.rowData);
  try {
    // 验证表单
    await validate();
    // 根据操作类型构造请求参数
    const params = {
      ...model.value
    };// 深拷贝，避免直接修改 model.value
    let response;
    const { hospId, ...restParams } = params;
    // 根据操作类型调用不同的接口
    switch (props.operateType) {
      case 'add':
        // 调用添加接口
        console.log(params);
        response = await fetchAddHosp(restParams);
        break;
      case 'edit':
        console.log(params);
        response = await fetchEditHosp(params);
        break;
      default:
        throw new Error('未知的操作类型');
    }
    console.log(response);
    // 根据接口返回结果处理
    if (response.error) {
      window.$message?.error($t('common.operationFailed'));
      return;
    }
    // 提示成功
    window.$message?.success($t('common.updateSuccess'));
    // 关闭抽屉
    closeDrawer();
    // 触发父组件的事件，通知更新表格数据
    emit('submitted');
  } catch (error) {
    // 捕获可能的错误
    console.error('Submit Error:', error);
    // 根据错误类型显示不同的提示
    const errorMessage = $t('common.operationFailed');
    window.$message?.error(errorMessage);
  }
}
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    // getRoleOptions();
  }
});
</script>
<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem :label="$t('page.manage.hosp.hospName')" path="hospName">
          <NInput v-model:value="model.hospName" :placeholder="$t('page.manage.hosp.form.hospName')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.hosp.hospLoc')" path="hospLoc">
          <NInput v-model:value="model.hospLoc" :placeholder="$t('page.manage.hosp.form.hospLoc')" />
        </NFormItem>
<!--        <NFormItem :label="$t('page.manage.hosp.userGender')" path="userGender">-->
<!--          <NRadioGroup v-model:value="model.userRole">-->
<!--            <NRadio v-for="item in userRoleOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />-->
<!--          </NRadioGroup>-->
<!--        </NFormItem>-->
<!--        <NFormItem :label="$t('page.manage.user.userPhone')" path="userPhone">-->
<!--          <NInput v-model:value="model.userPhone" :placeholder="$t('page.manage.user.form.userPhone')" />-->
<!--        </NFormItem>-->
<!--        <NFormItem :label="$t('page.manage.user.userEmail')" path="email">-->
<!--          <NInput v-model:value="model.userEmail" :placeholder="$t('page.manage.user.form.userEmail')" />-->
<!--        </NFormItem>-->
        <NFormItem :label="$t('page.manage.hosp.deleteFlag')" path="status">
          <NRadioGroup v-model:value="model.deleteFlag">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
<!--        <NFormItem :label="$t('page.manage.user.userRole')" path="roles">-->
<!--          <NSelect-->
<!--            v-model:value="model.userRoles"-->
<!--            multiple-->
<!--            :options="roleOptions"-->
<!--            :placeholder="$t('page.manage.user.form.userRole')"-->
<!--          />-->
<!--        </NFormItem>-->
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
